package com.ruoyi.exam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.exam.domain.ExamErrorQuestion;
import com.ruoyi.exam.vo.ExamErrorQuestionVo;
import com.ruoyi.exam.vo.ExamQuestionDetailVo;
import com.ruoyi.exam.vo.ExamQuestionOptionVo;
import com.ruoyi.exam.vo.SubmitAnswerVo;
import com.ruoyi.exam.vo.SubmitAnswerResultVo;
import com.ruoyi.exam.mapper.ExamErrorQuestionMapper;
import com.ruoyi.exam.service.IExamErrorQuestionService;
import com.ruoyi.exam.service.IExamQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户错题记录Service业务层处理
 *
 * @author Tellsea
 * @date 2025-10-27
 */
@Service
public class ExamErrorQuestionServiceImpl extends ServiceImpl<ExamErrorQuestionMapper, ExamErrorQuestion> implements IExamErrorQuestionService {

    @Autowired
    private IExamQuestionService examQuestionService;

    @Override
    public TableDataInfo<ExamErrorQuestionVo> queryList(ExamErrorQuestionVo entity) {
        return PageUtils.buildDataInfo(this.baseMapper.queryList(PageUtils.buildPage(), entity));
    }

    @Override
    public List<ExamErrorQuestionVo> queryAll(ExamErrorQuestionVo entity) {
        return this.baseMapper.queryList(entity);
    }

    @Override
    public ExamErrorQuestionVo queryById(Long id) {
        return this.baseMapper.queryById(id);
    }

    @Override
    public int addErrorQuestion(ExamErrorQuestionVo entity) {
        // 根据 user_id、bank_id、question_id 查询是否已存在记录
        LambdaQueryWrapper<ExamErrorQuestion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExamErrorQuestion::getUserId, entity.getUserId())
                .eq(ExamErrorQuestion::getBankId, entity.getBankId())
                .eq(ExamErrorQuestion::getQuestionId, entity.getQuestionId());
        
        long count = this.baseMapper.selectCount(queryWrapper);
        
        // 如果不存在记录，则新增
        if (count == 0) {
            ExamErrorQuestion examErrorQuestion = new ExamErrorQuestion();
            examErrorQuestion.setUserId(entity.getUserId());
            examErrorQuestion.setBankId(entity.getBankId());
            examErrorQuestion.setQuestionId(entity.getQuestionId());
            return this.baseMapper.insert(examErrorQuestion);
        }
        
        // 记录已存在，返回0
        return 0;
    }

    @Override
    public int deleteErrorQuestion(ExamErrorQuestionVo entity) {
        // 根据 user_id、bank_id、question_id 删除记录
        LambdaQueryWrapper<ExamErrorQuestion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExamErrorQuestion::getUserId, entity.getUserId())
                .eq(ExamErrorQuestion::getBankId, entity.getBankId())
                .eq(ExamErrorQuestion::getQuestionId, entity.getQuestionId());
        
        return this.baseMapper.delete(queryWrapper);
    }

    @Override
    public List<Long> queryErrorQuestionIdsByBank(Long userId, Long bankId) {
        return this.baseMapper.queryErrorQuestionIdsByBank(userId, bankId);
    }

    @Override
    public SubmitAnswerResultVo submitErrorAnswer(SubmitAnswerVo submitAnswerVo, Long userId) {
        // 1. 获取题目详细信息
        ExamQuestionDetailVo questionDetail = examQuestionService.queryDetailById(submitAnswerVo.getQuestionId(), userId);
        if (questionDetail == null) {
            throw new RuntimeException("题目不存在");
        }

        // 2. 判断答案是否正确
        boolean isCorrect = checkAnswer(questionDetail, submitAnswerVo);
        
        // 3. 如果答案正确，删除错题记录；如果答案错误，保留错题记录
        ExamErrorQuestionVo errorQuestion = new ExamErrorQuestionVo();
        errorQuestion.setUserId(userId);
        errorQuestion.setBankId(submitAnswerVo.getBankId());
        errorQuestion.setQuestionId(submitAnswerVo.getQuestionId());
        
        if (isCorrect) {
            // 答案正确，删除错题记录
            this.deleteErrorQuestion(errorQuestion);
        }
        // 答案错误，保留错题记录（不做任何操作）

        // 4. 构建返回结果
        SubmitAnswerResultVo result = new SubmitAnswerResultVo();
        result.setIsCorrect(isCorrect);
        result.setSelectedOptions(submitAnswerVo.getUserAnswer());
        
        // 获取正确选项
        List<String> correctOptions = questionDetail.getOptions().stream()
                .filter(option -> "1".equals(option.getIsCorrect()))
                .map(ExamQuestionOptionVo::getOptionLabel)
                .collect(Collectors.toList());
        result.setCorrectOptions(correctOptions);
        result.setQuestionAnalysis(questionDetail.getQuestionAnalysis());


        return result;
    }

    /**
     * 检查答案是否正确
     */
    private boolean checkAnswer(ExamQuestionDetailVo questionDetail, SubmitAnswerVo submitAnswerVo) {
        String questionType = questionDetail.getQuestionType();
        
        // 获取正确选项
        List<String> correctOptions = questionDetail.getOptions().stream()
                .filter(option -> "1".equals(option.getIsCorrect()))
                .map(ExamQuestionOptionVo::getOptionLabel)
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(correctOptions)) {
            return false;
        }

        // 客观题判断
        if ("1".equals(questionType) || "2".equals(questionType) || "3".equals(questionType)) {
            if (!StringUtils.hasText(submitAnswerVo.getUserAnswer())) {
                return false;
            }
            
            List<String> userOptions = Arrays.asList(submitAnswerVo.getUserAnswer().split(","));
            return userOptions.size() == correctOptions.size() && 
                   userOptions.containsAll(correctOptions);
        }
        
        // 主观题暂时返回true，实际需要人工判分
        return true;
    }
}
